const clientGroupId = localStorage.getItem("clientGroupId");
console.log("тут", clientGroupId);

let WebApp = window.Telegram.WebApp;
WebApp.expand();
WebApp.BackButton.hide();
WebApp.isClosingConfirmationEnabled = true;

const logOutButton = document.getElementById("logOut");
const scheduleMoreButton = document.getElementById("scheduleMoreButton");
let AllSсheduleItem = "";
const goToPayPage = document.getElementById("payLoad");
const innerLesson = document.querySelector(".scheduleBody");
const todaySchedule = document.getElementById("todaySchedule");

goToPayPage.addEventListener("click", () => {
  window.location.href = "/pay";
});

const request = [{ name: "next_lesson" }];
// console.log(request[0].name);

if (clientGroupId != "n/a" && clientGroupId != undefined) {
  // const urlLesson = `https://crm.caremybaby.ru/Remotes/tgwa_pc_get_records_QwhY655?request=${request[0].name}&client_number=${clientGroupId}`;

  // fetch("/nextlessons", {
  //   method: "POST",
  //   headers: {
  //     "Content-Type": "application/json",
  //   },
  //   body: JSON.stringify({ clientGroupId: clientGroupId }),
  // })
  //   .then((res) => res.json())
  //   .then((data) => {
  //     console.log("nextlesson", data);
  //     displayLesson(data);
  //   })
  //   .catch((err) => {
  //     console.log(err);
  //   });

  fetch("/nextlessons", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ clientGroupId: clientGroupId }),
  })
    .then((res) => {
      if (!res.ok) {
        throw new Error(
          `response was not ok (${res.status}: ${res.statusText})`
        );
      }
      return res.json();
    })
    .then((data) => {
      if (!data || typeof data !== "object" || Array.isArray(data)) {
        throw new Error("Invalid response from server");
      }
      consolelog("nextlesson", data);
      displayLesson(data);
    })
    .catch((err) => {
      console.error("There was an error!", err);
    });
}

let todayDate = new Date();
console.log(todayDate);

const displayLesson = (lesson) => {
  if (lesson.length > 0) {
    let flag = true;
    lesson.forEach(
      ({ lesson_name, lesson_date, teacher, lesson_date_for_js }, index) => {
        const match = lesson_date_for_js.match(/-?\d+(\.\d+)?/g);
        let lessonDay = parseInt(match[2]);
        let lessonMount = parseInt(match[1]);

        // console.log("тест", lessonMount);
        // console.log("rer", todayDate.getMonth());
        if (
          lessonDay == todayDate.getDate() &&
          lessonMount == todayDate.getMonth()
        ) {
          innerLesson.innerHTML += `
    <div class="scheduleItem">
      <div class="scheduleAbout">
        <h2 class="scheduleDate">
         ${lesson_date}
        </h2>
        <p class="sixe">${teacher}</p>
        <p class="sixe">${lesson_name}</p>
      </div>
    </div>`;
          flag = false;
        }
        if (lessonDay != todayDate.getDate() && flag) {
          todaySchedule.innerText = "На сегодня нет занятий";
          innerLesson.innerHTML = `
          <div class="scheduleItem">
            <div class="scheduleAbout">
              <h2 class="scheduleDate">
               Перейдите в расписание
              </h2>
            </div>
          </div>`;
        }
      }
    );
  } else {
    innerLesson.innerHTML += `
    <div class="scheduleItem">
      <div class="scheduleAbout">
        <h2 class="scheduleDate">
         Нет занятий в расписании
        </h2>
      </div>
    </div>`;
  }
  AllSсheduleItem = document.querySelectorAll(".scheduleItem");
  // console.log(AllSсheduleItem);
  for (let i = 0; i < AllSсheduleItem.length; i++) {
    console.log("Adding");
    AllSсheduleItem[i].addEventListener("click", goToSchedule);
  }
};

fetch("/materials")
  .then((res) => res.json())
  .then((data) => {
    // console.log("data", data);
    displayPopUp(data);
    displayMaterial(data);
  });

const popUp = document.getElementById("referrer");
const nameMaterialPopUp = document.getElementById("nameMaterialPopUp");
const descriptionPopUp = document.getElementById("descriptionPopUp");
const zero = document.getElementById("zero");

const innerPopUp = document.querySelector(".material");

const displayMaterial = (data) => {
  const test = document.querySelectorAll(".openPopUp");
  console.log(test);
  for (let i = 0; i < test.length; i++) {
    test[i].addEventListener("click", () => {
      console.log(data[i].name);
      popUp.style.display = "flex";
      nameMaterialPopUp.innerText = data[i].name;
      descriptionPopUp.innerText = data[i].about;
      zero.style.backgroundImage = `url(${data[i].src})`;
    });
  }
};

const displayPopUp = (data) => {
  data.forEach(({ name, src }, index) => {
    // console.log(name, src);

    innerPopUp.innerHTML += `
        <div class="openPopUp" value="0">
            <img class="imgContainer" src="${src}"/>
            <h3 class="labelFromImg">${name}</h3>
        </div>`;
  });
};

popUp.addEventListener("click", (e) => {
  if (e.target.id === "referrer") {
    popUp.style.display = "none";
  }
});

const closePopUpButton = document.getElementById("closeBtn1");

closePopUpButton.addEventListener("click", () => {
  popUp.style.display = "none";
});

const goToSchedule = () => {
  window.location.href = "/schedule/";
};

scheduleMoreButton.addEventListener("click", goToSchedule);
// sсheduleItem.addEventListener("click", goToSchedule);

// alert(getDeviceType()); // "mobile" or "desktop"

//Выход из ЛК
logOutButton.addEventListener("click", () => {
  console.log("ok");
  localStorage.setItem("clientGroupId", "n/a");
  localStorage.setItem("phoneNumber", "n/a");
  window.location.href = "/index.html";
});

const innerSlideBar = document.querySelector(".owerFlowWindod");

fetch("/banners")
  .then((res) => res.json())
  .then((data) => {
    // console.log("data", data);
    displayBanners(data);
  });

const displayBanners = (data) => {
  data.forEach(({ name, src, about }, index) => {
    // console.log(name, src);

    innerSlideBar.innerHTML += `
    <div class="slide" style="background-image: url('${src}');">
    <h2 class="h3Ower">${name}</h2>
    <p class="tooltip">${about}</p>
  </div>`;
  });
};

// --------- кнопка регистрации

const regButton = document.getElementById("regis");

regButton.addEventListener("click", () => {
  window.location.href = "/registration/";
});

/// -------------

// const testApiGo = document.getElementById("testApiGo");

// testApiGo.addEventListener("click", () => {
//   // window.location.href = "/testApi/";
//   fetch("./name")
//     .then((response) => response.json())
//     .then((data) => {
//       console.log(data);
//     })
//     .catch((err) => {
//       console.log(err);
//     });
// });

// WebApp.MainButton.show();

// let xhrURL = new URL('https://t.me/$dx8tkGfOwEoMCQAAkb_kMv_dLuE');
// xhrURL.searchParams.set('title', ...);
/* ... setting other non-private optional parameters */

// let xhr = new XMLHttpRequest();
// xhr.open('GET', xhrURL);
// xhr.send();
// xhr.onload = function() {
//     WebApp.openInvoice(JSON.parse(xhr.response).result);
// }

// WebApp.MainButton.onClick(() => {
//   console.log("test");
//   let xhrURL = new URL("https://t.me/$dx8tkGfOwEoMCQAAkb_kMv_dLuE");
//   // console.log(xhrURL);
//   console.log(xhrURL);
//   // let xhr = new XMLHttpRequest();
//   // xhr.open("GET", xhrURL);
//   // xhr.send();
//   fetch(xhrURL, {
//     method: "GET",
//     mode: "no-cors",
//   })
//     .then((response) => {
//       console.log(response);
//     })
//     // .then((data) => {
//     //   console.log(response);
//     // })
//     .catch((error) => {
//       console.log(error);
//     });

//   // WebApp.openInvoice(JSON.parse(xhr.response).result);

//   //WebApp.openLink(`https://t.me/$dx8tkGfOwEoMCQAAkb_kMv_dLuE`);
// });
// // invoice_url: "https://t.me/$dx8tkGfOwEoMCQAAkb_kMv_dLuE"
